package org.springleaf.utils;

import java.text.SimpleDateFormat;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

/**
 * BeanUtils的日期转换
 * @author leaf
 *
 */
@Component
@SuppressWarnings("rawtypes")
public class DateConvert implements Converter, BeanFactoryAware{

	public Object convert(Class classz, Object v) {
		String p = (String) v;
		if (p == null || p.trim().length() == 0) {
			return null;
		}
		try {
			if (p.length() > 13) {
				SimpleDateFormat df = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				return df.parse(p.trim());
			} else {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				return df.parse(p.trim());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public void setBeanFactory(BeanFactory factory) throws BeansException {
		ConvertUtils.register(this, java.util.Date.class);
	}

}
